﻿using RightControl.Common;
using RightControl.IService;
using RightControl.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AlibabaCollector {
   public class InterfaceAnalyser {

       public static IProductService productService { get; set; }
       public static IProductImgService productImgService { get; set; }
       public static ISubProductImageService subProductImageService { get; set; }

       public static ISubProductSizeService subProductSizeService { get; set; }

       public static string urlPattern = @"(http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%!&=]*)?)";


       public static ProductDetail GetDetail(string url, int userId, string category, List<ExportFields> exportfields) {
           ProductDetail prdDetail = new ProductDetail(url, userId, category);
           try {
               int productId = -1;
               if (productService.IsNotExist(prdDetail)) {
                   prdDetail.SkuId = category + Common.RandomChar(2);
                   string itemId = HtmlUtils.GetMatchedStr("/(\\d+).html", url);
                   dynamic ret = GetReuslt(itemId);
                   if (ret != null) {
                       productId = CreateProductDetail(prdDetail, ret, exportfields);

                       List<ProductImage> imageList = new List<ProductImage>();
                       if (ret.data.images != null) {
                           for (int i = 0; i < ret.data.images.Count; i++) {
                               if (imageList.FindAll(b => b.ImgUrl == ret.data.images[i].Value).Count == 0) {
                                   imageList.Add(new ProductImage(productId, ret.data.images[i].Value, 1, userId, i + 1));
                               }                            
                           }
                       }

                       if (ret.data.desc != null) {
                           List<string> imgList = HtmlUtils.GetMatchedList(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", ret.data.desc.Value);
                           for (int i = 0; i < imgList.Count; i++) {
                               imageList.Add(new ProductImage(productId, imgList[i], 2, userId, i + 1));
                           }
                       }
                       productImgService.SaveImages(imageList);

                       if (ret.data.skuProps != null) {
                            string imgUrl;
                           List<SubProductImage> subProductImageList = new List<SubProductImage>();
                           List<SubProductSize> subProductSizeList = new List<SubProductSize>();
                           Dictionary<string, string> sizeMap = new Dictionary<string, string>();
                           sizeMap["1XL"] = "XL";
                           sizeMap["XXL"] = "2XL";
                           sizeMap["XXXL"] = "3XL";
                           sizeMap["XXXXL"] = "4XL";

                           for (int i = 0; i < ret.data.skuProps.Count; i++) {
                               if (ret.data.skuProps[i].prop.Value == "颜色") {
                                   if (ret.data.skuProps[i].value != null) {
                                       for (int j = 0; j < ret.data.skuProps[i].value.Count; j++) {
                                           imgUrl = ret.data.skuProps[i].value[j].imageUrl != null ? ret.data.skuProps[i].value[j].imageUrl.Value : "";
                                           string color = ret.data.skuProps[i].value[j].name.Value;
                                           color = color.Length > 10 ? "" : color;
                                           subProductImageList.Add(new SubProductImage(productId, color, imgUrl, userId));
                                       }
                                   }
                               }
                               else if (ret.data.skuProps[i].prop.Value == "尺码") {
                                   if (ret.data.skuProps[i].value != null) {
                                       for (int j = 0; j < ret.data.skuProps[i].value.Count; j++) {
                                           string size = ret.data.skuProps[i].value[j].name.Value;
                                           size = size.Length > 15 ? "" : size;
                                           size = sizeMap.ContainsKey(size) ? sizeMap[size] : size;
                                           subProductSizeList.Add(new SubProductSize(productId, size, prdDetail.Price, userId));
                                       }
                                   }
                               }
                           }
                           int saveSizeRet = subProductSizeService.SaveSubProductSize(subProductSizeList);
                           int saveImageRet = subProductImageService.SaveSubProductImages(subProductImageList);
                       }
                   }
               }
           }
           catch (Exception ex) {
               LogHelper.WriteWebLog("GetDetail异常", ex);
           }
           return prdDetail;
       }

       private static int CreateProductDetail(ProductDetail prdDetail, dynamic ret, List<ExportFields>  exportfields) {
           if (ret.data.attributes != null) {
               string[] attr;
               Dictionary<string, string> detailConfig = new Dictionary<string, string>();
               for (int i = 0; i < ret.data.attributes.Count; i++) {
                   attr = (ret.data.attributes[i].Value as string).Split(':');
                   detailConfig[attr[0]] = attr[1];
               }
               Dictionary<string, string> keyAttributs = new Dictionary<string, string>();
               if (exportfields != null) {                 
                   exportfields.ForEach(h => {
                       keyAttributs[h.FieldName] = detailConfig.ContainsKey(h.FieldName) ? detailConfig[h.FieldName] : "";
                   });
               }
               prdDetail.Description = SerializerHelper.JsonSerialized<Dictionary<string, string>>(detailConfig);
               prdDetail.KeyAttributes = SerializerHelper.JsonSerialized<Dictionary<string, string>>(keyAttributs);
           }
           prdDetail.ImageUrl = ret.data.images != null ? ret.data.images[0].Value : "";
           prdDetail.Title = ret.data.title.Value;
           prdDetail.CategoryId = ret.data.categoryId.Value;
           string price = ret.data.displayPrice.Value;
           price = price.Replace("￥", "");
           prdDetail.Price = price.IndexOf("-") < 0 ? price.ToDecimal() : price.Split('-')[1].ToDecimal();//取价高者
           int productId = productService.InsertModel(prdDetail);
           return productId;
       }

       private static dynamic GetReuslt(string itemId) {
           HttpHelper httpHelper = new HttpHelper();
           HttpItem httpItem = new HttpItem();
           httpItem.URL = "https://api03.6bqb.com/alibaba/app/detail?apikey=08B7EB9C2122D1ACC4A0578BB9132185&itemId=" + itemId;
           httpItem.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
           httpItem.UserAgent = "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5";
           httpItem.SecurityProtocolType = SecurityProtocolType.Tls;
           HttpResult result = httpHelper.GetHtml(httpItem);

           return result != null ? SerializerHelper.JsonDeserialized<dynamic>(result.Html) : null;
       }


    }
}
